<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/10/12
 * Time: 10:50
 */

namespace app\portal\controller;
use cmf\controller\HomeBaseController;
use app\portal\model\PortalPostModel;
use app\portal\model\PortalCategoryModel;
use app\portal\model\ActivityLogModel;
use app\portal\model\UserRankModel;
use app\portal\model\PointExchangeLogModel;
use app\portal\model\UserOrganizeModel;
use app\portal\model\UserModel;
use Firebase\JWT\JWT;
use cmf\phpqrcode\QRcode;
use think\facade\Env;

use think\Db;


class PersonalController extends HomeBaseController
{
    private $user_id;
    public function tests(){
//        $content=Db::name('portal_post')->where('id',30)->value('post_content');
//        dump($content);
//        $content=html_entity_decode($content);
//        $imgs=cmf_get_content_first_image($content);
       // $imgs=cmf_get_image_url($imgs);
//        dump($imgs);
        $key = "rzjj";
        $token = [
            "iss"=>"shuker",
            "aud"=>"",
            "iat" => time(),
            "nbf" => time()+1,
            "exp" => time()+7200,
            "uid" => 123
        ];
        $jwt=new JWT;
        $data =$jwt->encode($token,$key,"HS256");
        return json([
            "token"=>$data
        ]);
    }



    public function initialize(){
        $this->user_id=cmf_get_current_user_id();
        if($this->user_id<=0){
            /**判断用户是否登陆*/
            $this->redirect('/portal/index/login');
        }
        $sel=Db::name('user_organize')->where('user_id',$this->user_id)->where('status',1)->select();
        if (count($sel)==0){
            /**根据是否已经是志愿者判断能不能看这个页面*/
            $this->redirect('/portal/index/apply');
        }
    }

    public function index()
    {
        $user=session('user');
        $this->assign('user',$user);
        return $this->fetch(':personal');
    }
    //个人活动
    public function per_activity()
    {
        $model=new ActivityLogModel();
        $list=$model->where('user_id',$this->user_id)->with('activity')->order('ctime desc')->paginate(10);
        $this->assign('list',$list);
        $this->assign('page',$list->render());
        return $this->fetch(':personalActivity');
    }
    //个人文章
    public function per_article()
    {
        $model=new PortalPostModel();
        $list=$model->where('user_id',$this->user_id)->order('id desc')->paginate(10);
        $this->assign('list',$list);
        //dump($list);
        $this->assign('page',$list->render());
        return $this->fetch(':personalArticle');
    }
    //个人数据页面
    public function per_data()
    {
        $user_model=new UserModel();
        $user=$user_model->with('groups')->with('communities')->where('id',$this->user_id)->find();
        unset($user['user_pass']);
        //$more=json_decode($user['more'],true);
        $car_info=Db::name('user_info')->where('user_id',$user['id'])->find();
        $group=Db::name('organize_child')->select();
        //dump($car_info);
        $sex=['','男','女'];
        $this->assign('sex',$sex);
        $this->assign('group',$group);
        $this->assign('user',$user);
        $this->assign('more',$user['more']);
        $this->assign('car_info',$car_info);
        return $this->fetch(':personalData');
    }
    //保存个人数据页面
    //ajax检验身份证号
    function check_idcard($idcard){

        // 只能是18位
        if(strlen($idcard)!=18){
            return '长度不够';
        }
        // 取出本体码
        $idcard_base = substr($idcard, 0, 17);
        // 取出校验码
        $verify_code = substr($idcard, 17, 1);
        // 加权因子
        $factor = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        // 校验码对应值
        $verify_code_list = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
        // 根据前17位计算校验码
        $total = 0;
        for($i=0; $i<17; $i++){
            $total += substr($idcard_base, $i, 1)*$factor[$i];
        }
        // 取模
        $mod = $total % 11;
        // 比较校验码
        if($verify_code == $verify_code_list[$mod]){
            return '输入正确';
        }else{
            return '校验不通过';
        }
    }

    public function save_user_info(){
        $input=input('post.');
       // dump($input);exit;
        $data=[];
        $data['birthday']=strtotime(substr($input['more']['idcard'],6,8));
        if($input['more']['idcard'][-2]%2==1){
            $data['sex']=1;
        }else{
            $data['sex']=2;
        }
        $data['avatar']=$input['avatar'];
        $data['more']=json_encode($input['more']);
        $model=new UserModel();
        $result = $model->where('id',$this->user_id)->update($data);
        if ($result === false) {
            $this->error('修改个人信息失败！');
        }
        $user=session('user');
        $data['more']=json_decode($data['more'],true);
        $user=array_replace($user,$data);
        session('user',$user);
        $this->success('修改个人信息成功！');

    }
    //保存车辆信息
    public function  save_car_info(){
       $data=input('post.');
        unset($data['file']);
        $data['user_id']=$this->user_id;
//        $data['start_time']=strtotime($data['start_time']);
        if($data['car_card']!=''&&$data['img_a']!=''&&$data['img_b']!=''){
            $res=Db::name('user_info')->insert($data);
            if($res){
                $this->success('添加车辆信息成功！',url('portal/Personal/per_data'));
            }else{
                $this->error('添加车辆信息失败！',url('portal/Personal/per_data'));
            }
        }else{
            $this->error('请确保信车辆息完整~');
        }

    }
    //修改密码
    public function change_pass(){
    $model = new UserModel();
        $password=input('old_pass');
        $new_pass=input('new_pass');
        $sure_pass=input('sure_pass');
        $user=session('user');
        $passwordInDb=$model->where('id',$user['id'])->value('user_pass');
        if($new_pass!=$sure_pass){
            $this->error('两次输入不一致',url('portal/Personal/per_data'));
        }
       if(!cmf_compare_password($password, $passwordInDb)){
           $this->error('初始密码不正确',url('portal/Personal/per_data'));
       }
       if($new_pass==$password){
           $this->error('新旧密码不要相同',url('portal/Personal/per_data'));
       }
       $data=['user_pass'=>cmf_password($new_pass)];
       $res=Db::name('user')->where('id',$this->user_id)->update($data);
        if($res){
            $this->success('修改密码成功！',url('portal/Personal/per_data'));
        }else{
            $this->error('修改密码失败！',url('portal/Personal/per_data'));
        }
    }
    //保存头像
    public function save_avatar(){
        $avatar=input('avatar');
        $res=Db::name('user')->where('id',$this->user_id)->update(['avatar'=>$avatar]);
        if($res){
            $this->success('修改头像成功！');
        }else{
            $this->error('修改头像失败~');
        }
    }
    //个人积分
    public function per_integral()
    {
        $model =new UserOrganizeModel();
        $log = new PointExchangeLogModel();
        $list=$log->with('goods')->where('user_id',$this->user_id)->order('id desc')->select();
        $data=$model->with('user')->where('user_id',$this->user_id)->find();
        $points=Db::name('exchange_goods')->where(['status'=>1,'type'=>1])->select();
        $goods=Db::name('exchange_goods')->where(['status'=>1,'type'=>0])->select();
        $this->assign('goods',$goods);
        $this->assign('points',$points);
        $this->assign('data',$data);
        $this->assign('list',$list);
        return $this->fetch(':personalIntegral');
    }
    //积分兑换
//    public function exchange(){
//        $result=[];
//        $result['msg']='暂未开放~~';
//        return $result;
//        $id=input('id');
//        $user_id=$this->user_id;
//        $goods=Db::name('exchange_goods')->where('id',$id)->find();
//        $find=Db::name('user_rank')->where('user_id',$user_id)->find();
//        //判断兑换权限,剩余积分，车辆信息状态
//        $car_info=Db::name('user_info')->where('user_id',$user_id)->find();
//
//        if($goods['point']>$find['can_points']){
//            $result['msg']='积分不足以兑换该商品';
//            return $result;
//        }
//        if($goods['type']==1){
//            $begin_year = strtotime(date("Y",time())."-1"."-1"); //本年开始
//            $end_year = strtotime(date("Y",time())."-12"."-31"); //本年结束
//            //需要验证车辆信息
//            if(count($car_info)==0){
//                $result['msg']='请先完善车辆信息';
//                return $result;
//            }
//            $arr=[$begin_year,$end_year];
////            dump($arr);
//            $points=Db::name('point_exchange_log')->where('user_id',$user_id)->where('goods_id','in',[1,2,3])->where('ctime','between',$arr)->sum('point');
//            if($points+$goods['point']>12){
//                $result['msg']='一自然年周期最多兑换12分！';
//                return $result;
//            }
//            $key = "rzjj";
//            $token = [
//                "iss"=>"shuker",
//                "aud"=>"",
//                "iat" => time(),
//                "nbf" => time(),
//                "exp" => time()+60*60*24*366,
//                'car_num'=>$car_info['car_card']
//            ];
//            $jwt=new JWT;
//            $check_code =$jwt->encode($token,$key,"HS256");
//            $array=['user_id'=>$user_id,'code'=>$check_code,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id];
//            Db::startTrans();
//            try{
//                $id=Db::name('point_exchange_log')->insertGetId($array);
//                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
//                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
//                $token['uid']=$id;
//                $token['code']=$check_code;
//                $res=$this->test($key,$token);
//                if($res['err_code']==0){
//                    throw new \Exception($res['msg']);
//                }else{
//                    Db::commit();
//                    $result['msg']='兑换成功';
//                }
//            }catch (\Exception $e){
//                $result['msg']='兑换失败';
//                Db::rollback();
//            }
//        }else{
//            Db::startTrans();
//            try{
//                $data=['user_id'=>$user_id,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id,'code'=>uniqid()];
//                Db::name('point_exchange_log')->insert($data);
//                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
//                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
//                Db::commit();
//                $result['msg']='兑换成功';
//            }catch (\Exception $e){
//                $result['msg']='兑换失败';
//                Db::rollback();
//            }
//        }
//
//        return $result;
//    }

/**积分兑换2.0*/
    public function exchange(){
        $result=[];
        $id=input('id');
        $user_id=$this->user_id;
        $goods=Db::name('exchange_goods')->where('id',$id)->find();
        $find=Db::name('user_rank')->where('user_id',$user_id)->find();
        //判断兑换权限,剩余积分，车辆信息状态
        $car_info=Db::name('user_info')->where('user_id',$user_id)->find();

        if($goods['point']>$find['can_points']){
            $result['msg']='积分不足以兑换该商品';
            return $result;
        }
        if($goods['type']==1){
            $begin_year = strtotime(date("Y",time())."-1"."-1"); //本年开始
            $end_year = strtotime(date("Y",time())."-12"."-31"); //本年结束
            //需要验证车辆信息
            if(count($car_info)==0){
                $result['msg']='请先完善车辆信息';
                return $result;
            }
            $arr=[$begin_year,$end_year];
//            dump($arr);
            $points=Db::name('point_exchange_log')->where('user_id',$user_id)->where('goods_id','in',[1,2,3])->where('ctime','between',$arr)->sum('point');
            if($points+$goods['point']>12){
                $result['msg']='一自然年周期最多兑换12分！';
                return $result;
            }
            $key = "rzjj";
            $token = [
                "iss"=>"shuker",
                "aud"=>"",
                "ctime" => time(),
                "start_time" => time(),
                "end_time" => time()+60*60*24*366,
                "user_id"=>$user_id,
                "point"=>$goods['point'],
                'car_num'=>$car_info['car_card']
            ];
            $jwt=new JWT;
            $check_code =$jwt->encode($token,$key,"HS256");
            $url=$check_code;
            //$base_url  = request()->domain();
           // $url=$base_url.'/portal/admin_weixin/check_points?check_code='.$check_code;

            $qrcode=$this->qrcode($url);
            $array=['user_id'=>$user_id,'code'=>$check_code,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id,'qrcode'=>$qrcode];
            Db::startTrans();
            try{
                Db::name('point_exchange_log')->insertGetId($array);
                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
                Db::commit();
                $result['msg']='兑换成功';
                $result['error']=1;
            }catch (\Exception $e){
                $result['msg']='兑换失败'.$e->getMessage();
                $result['error']=0;
                Db::rollback();
            }
        }else{
            Db::startTrans();
            try{
                $data=['user_id'=>$user_id,'point'=>$goods['point'],'ctime'=>time(),'goods_id'=>$id,'code'=>uniqid()];
                Db::name('point_exchange_log')->insert($data);
                Db::name('user_rank')->where('user_id',$user_id)->setInc('used_points',$goods['point']);
                Db::name('user_rank')->where('user_id',$user_id)->setDec('can_points',$goods['point']);
                Db::commit();
                $result['error']=1;
                $result['msg']='兑换成功';
            }catch (\Exception $e){
                $result['error']=0;
                $result['msg']='兑换失败'.$e->getMessage();
                Db::rollback();
            }
        }

        return $result;
    }

    //积分兑换测试
//    public function test($key,$array){
//        $result=[];
//        $_key = "rzjj";
//        if($_key==$key){
//            $save=true;
//            if($save){
//                $result['msg']='保存成功';
//                $result['err_code']=1;
//            }else{
//                $result['msg']='保存失败';
//                $result['err_code']=0;
//            }
//        }
//        return $result;



//        $token='helloworld';
//        $url='http://www.justmetu.top/index/test/api?token='.$token;
//        $point=1;
//        $data=['car_num'=>'鲁L12345','point'=>$point];
//        $result=$this->http_post($url,$data);
//        $array=json_decode($result,true);
//        $code=json_decode($array['code']);
//        $result=[];
//        if($array['msg']==1){
//            Db::name('user_rank')->where('user_id',$this->user_id)->setDec('can_points',$point);
//            Db::name('user_rank')->where('user_id',$this->user_id)->setInc('used_points',$point);
//            //兑换成功，扣除积分
//            $result['msg']='兑换成功';
//        }else{
//            $result['msg']='兑换失败';
//        }
//        dump($code);
//        dump($array);
//    }

    function http_post($url,$data){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER,array());
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function get_data(){
        $user=Db::name('user')->where('id',29)->find();
        $user['more']=json_decode($user['more'],true);
        dump($user);
    }

    //删除积分记录
    public function log_del(){
        $Model = new PointExchangeLogModel();
        $id= $this->request->param('id');
        $result=$Model->where('id',$id)->delete();
        if ($result) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }

    //添加文章
//    public function article_add()
//    {
//        return $this->fetch(':newArticle');
//    }
    //修改文章
    public function article_edit(){

        $model = new PortalCategoryModel();
        $id = $this->request->param('id', 0, 'intval');
        $portalPostModel = new PortalPostModel();
        $post            = $portalPostModel->where('id', $id)->find();
        $cate_id=Db::name('portal_category_post')->where('post_id',$id)->value('category_id');
        $this->assign('post', $post);
        $category=$model->where('parent_id',6)->column('id,name');
        $category[6]='志愿服务心得';
        $this->assign('category',$category);
        $this->assign('cate_id',$cate_id);
        return $this->fetch(':editArticle');
    }

    //保存发布文章
    public function addPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            //状态只能设置默认值。未发布、未置顶、未推荐
            $data['post']['post_status'] = 0;
            $data['post']['is_top']      = 0;
            $data['post']['recommended'] = 0;
            $post = $data['post'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }
            $portalPostModel = new PortalPostModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }
            $data['post']['user_id'] = cmf_get_current_user_id();

            $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);

            $data['post']['id'] = $portalPostModel->id;
            $hookParam          = [
                'is_add'  => true,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);


            $this->success('添加成功!', url('per_article'));
        }

    }

    //保存修改文章
    public function editPost()
    {

        if ($this->request->isPost()) {
            $data = $this->request->param();
            $post   = $data['post'];
            $result = $this->validate($post, 'AdminArticle');
            if ($result !== true) {
                $this->error($result);
            }

            $portalPostModel = new PortalPostModel();

            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
                $data['post']['more']['photos'] = [];
                foreach ($data['photo_urls'] as $key => $url) {
                    $photoUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
                }
            }

            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
                $data['post']['more']['files'] = [];
                foreach ($data['file_urls'] as $key => $url) {
                    $fileUrl = cmf_asset_relative_url($url);
                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
                }
            }

            $portalPostModel->adminEditArticle($data['post'], $data['post']['categories']);

            $hookParam = [
                'is_add'  => false,
                'article' => $data['post']
            ];
            hook('portal_admin_after_save_article', $hookParam);

            $this->success('修改成功!', url('per_article'));

        }
    }

    //删除个人文章
    public function article_del(){
        $Model = new PortalPostModel();
        $id= $this->request->param('id');
        $result=$Model->where('id',$id)->delete();
        if ($result) {
            $this->success('删除成功!');
        } else {
            $this->error('删除失败');
        }
    }
    //生成二维码
    public function qrcode($url){
        $errorCorrectionLevel = 'L';
        $matrixPointSize = 5;
        $folder_path = Env::get('root_path').'public'.DIRECTORY_SEPARATOR.'upload'.DIRECTORY_SEPARATOR.'qrcode'.DIRECTORY_SEPARATOR;
        $uuid = uniqid();
        $filename = $folder_path.$uuid.'.png';
        if(!is_dir($folder_path)){
            mkdir($folder_path,0777,true);
        }
        try{
            QRcode::png($url,$filename , $errorCorrectionLevel, $matrixPointSize, 2);
        }catch(\Exception $e){
            return false;
        }

        return $uuid;
    }



}